package main

import (
	"fmt"
	"io"
	"net"
	"net/http"

	"gitee.com/spark-community-works-collections/shenmo-water-pipe/utils"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func main() {
	go ProxyTranformer()
	ginServer()
}

func ginServer() {
	gin.SetMode(gin.DebugMode)

	r := gin.Default()
	r.Use(cors.Default())

	r.GET("/api/dog", func(ctx *gin.Context) {
		resp, err := http.Get("https://dog.ceo/api/breeds/image/random")
		if err != nil {
			ctx.JSON(404, gin.H{})
		}
		defer resp.Body.Close()
		io.Copy(ctx.Writer, resp.Body)
	})

	r.Run(":8080")
}

func ProxyTranformer() {
	var from, to = 8888, 7777
	froml, _ := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%v", from))
	tol, _ := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%v", to))

	for {
		fromc, _ := froml.Accept()
		fmt.Printf("fromc: %v\n", fromc)
		toc, _ := tol.Accept()
		fmt.Printf("toc: %v\n", toc)

		go utils.TransferData(fromc, toc)
		go utils.TransferData(toc, fromc)
	}

}

func ProxyPortDirect() {
	var from, to = 8888, 8080
	froml, _ := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%v", from))

	for {
		fromc, _ := froml.Accept()
		fmt.Printf("fromc: %v\n", fromc)
		toc, _ := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%v", to))
		fmt.Printf("toc: %v\n", toc)

		go utils.TransferData(fromc, toc)
		go utils.TransferData(toc, fromc)
	}
}
